package com.liao.note.service.impl;

import com.liao.note.dao.CategoryDao;
import com.liao.note.dao.NoteDao;
import com.liao.note.dao.UserDao;
import com.liao.note.domain.Category;
import com.liao.note.domain.Note;
import com.liao.note.domain.User;
import com.liao.note.service.NoteService;
import com.liao.note.service.UserService;
import com.liao.note.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

/**
 * (User)表服务实现类
 *
 * @author long
 * @since 2023-02-11 19:59:09
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private NoteDao noteDao;
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public UserVO login(String account, String password) {
        UserVO userVO = null;
        User user = userDao.login(account, password);
        if (user != null) {
            userVO = new UserVO();
            ArrayList<Note> notes = noteDao.queryByUserId(user.getId());
            ArrayList<Category> categories = categoryDao.queryByUserId(user.getId());
            userVO.setUser(user);
            userVO.setNotes(notes);
            userVO.setCategories(categories);
            userVO.setNoteCount(notes.size());
            int i = 0;
            for (Note note : notes) {
                Integer size = note.getSize();
                i += size;
            }
            userVO.setWordCount(i);
        }
        return userVO;
    }

    @Override
    public String register(User user) {
        String account = createAccount();
        user.setAccount(account);
        user.setRegisterDate(new Date());
        int register = userDao.register(user);
        if (register > 0) {
            return account;
        }
        return "";
    }

    @Override
    public boolean updatePwd(User user) {
        User user1 = new User();
        user1.setId(user.getId());
        user1.setPassword(user.getPassword());
        if (userDao.update(user1) > 0) {
            return true;
        }
        return false;
    }

    public String createAccount() {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            s.append((int) (Math.random() * 10));
        }
        return s.toString();
    }
}
